package com.woniu.order.service.impl;
import com.woniu.model.PagePayParam; // 确保导入正确的类型
import cn.hutool.core.lang.Snowflake;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.exception.userexp.YogaException;
import com.woniu.order.Param.OrderPayParam;
import com.woniu.order.client.ProductClient;
import com.woniu.order.model.*;
import com.woniu.order.dao.CurriculumOrderDao;
import com.woniu.order.service.CurriculumOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.util.AlipayUtil;
import com.woniu.util.RedisKeyUtil;
import com.woniu.util.StateUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 杜岷芫
 * @since 2024年07月12日
 */
@Service
public class CurriculumOrderServiceImpl extends ServiceImpl<CurriculumOrderDao, CurriculumOrder> implements CurriculumOrderService {

    @Resource
    private ProductClient productClient;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private AlipayUtil alipayUtil;



    @Override
    public String pay(OrderPayParam Param) throws Exception {
        //1.检验进来的参数是否正确
        QueryWrapper<CurriculumOrder>wrapper = new QueryWrapper<>();
        wrapper.eq("order_num", Param.getOrderNum());
        CurriculumOrder curriculumOrder = baseMapper.selectOne(wrapper);
        if (!Objects.equals(curriculumOrder.getOrderState(),StateUtil.ORDER_STATE_NOT_PAY)){
            throw new YogaException(500,"订单状态异常");
        }
        if (curriculumOrder==null||!Objects.equals(curriculumOrder.getOrderNum(),Param.getOrderNum())){
            throw new YogaException(500,"订单不存在，请检查");
        }
        //组合参数
        PagePayParam payParam = new PagePayParam(); // 创建正确类型的对象
        payParam.setBody("瑜伽订单支付");
        payParam.setMoney(curriculumOrder.getOrderMoney().doubleValue());
        payParam.setNotifyUrl("http://xhrs7j.natappfree.cc/order/CurriculumOrder/notify");
        payParam.setReturnUrl("http://localhost:9091/#/UserMyOrder");
        payParam.setOrderId(curriculumOrder.getOrderNum());
        payParam.setSubject("yoga");
        //取出数据库订单的时间
        long expireTime = Date.from(LocalDateTime.parse(curriculumOrder.getFoundDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).plusMinutes(25).atZone(ZoneId.systemDefault()).toInstant()).getTime();
        long now = new Date().getTime();
        int minute = (int)((expireTime - now)/1000/60);
        if (minute<1){
            curriculumOrder.setOrderState(StateUtil.ORDER_STATE_CANCEL);
            baseMapper.updateById(curriculumOrder);
            throw new YogaException(500,"订单超时");
        }
        Date date = new Date(expireTime);
        String expire = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        System.out.println(expire);
        payParam.setTimeExpire(expire);//可支付的时间
        //调用支付宝工具类
        String s = alipayUtil.pagePay(payParam);
        return s;
    }

    @Override
    public List<CurriculumOrder> loadClassOrderByUserId(Integer userId, Integer orderState) {
        QueryWrapper<CurriculumOrder> wrapper = new QueryWrapper<CurriculumOrder>().eq("user_id", userId);
        if (orderState != null){
            if (orderState.equals(StateUtil.ORDER_STATE_NOT_PAY) || orderState.equals(StateUtil.ORDER_STATE_PAYED) ||orderState.equals(StateUtil.ORDER_STATE_CANCEL) || orderState.equals(StateUtil.ORDER_STATE_NOT_EVALUATE) || orderState.equals(StateUtil.ORDER_STATE_EVALUATE)){
                wrapper.eq("order_state",orderState);
            }

        }
        List<CurriculumOrder> orders = baseMapper.selectList(wrapper);
        return orders;
    }

    @Override
    public String orderLeagueClass(Integer userId, Integer groupLessonsClassId) throws Exception {
        RLock fairlock  = redissonClient.getFairLock(RedisKeyUtil.scheduleClassIdLock(groupLessonsClassId));
        RLock fairlock1 = redissonClient.getFairLock(RedisKeyUtil.userShoppingCar(userId));
        RLock lock = redissonClient.getMultiLock(fairlock,fairlock1);
        String s;
        try {
            boolean success  = lock.tryLock(20, TimeUnit.MILLISECONDS);
            if (success){
                LeagueClass leagueClass = productClient.ByIdLeagueClass(groupLessonsClassId).getData();
                if (leagueClass ==null){
                    throw new YogaException(3301,"不存在该团课");
                }
                List<CurriculumOrder> courseOrderList = baseMapper.selectList(new QueryWrapper<CurriculumOrder>().eq("course_id", groupLessonsClassId).ne("order_state", StateUtil.ORDER_STATE_CANCEL));
                if (courseOrderList.size()>=leagueClass.getClassNum()){
                    throw new YogaException(3459,"购买人数以达到上限");
                }
                CurriculumOrder curriculumOrder = new CurriculumOrder();
                String orderNum = new Snowflake(1,1).nextIdStr();
                curriculumOrder.setOrderNum(orderNum);
                curriculumOrder.setVenueId(leagueClass.getVenueId());
                curriculumOrder.setCurriculumId(groupLessonsClassId);
                curriculumOrder.setOrderMoney(leagueClass.getPrice().multiply(new BigDecimal(leagueClass.getClassNum())));
                curriculumOrder.setFoundDate(String.valueOf(LocalDateTime.now()));
                curriculumOrder.setOrderState(StateUtil.ORDER_STATE_NOT_PAY);
                curriculumOrder.setOrderPaytime(String.valueOf(LocalDateTime.now()));
                curriculumOrder.setRemark("用户ID: " + userId + "购买了团课，课程ID: " + groupLessonsClassId);
                curriculumOrder.setFinishTime(String.valueOf(LocalDateTime.now()));
                curriculumOrder.setPayType(1);
                curriculumOrder.setOrderNum(String.valueOf(leagueClass.getClassNum()));
                curriculumOrder.setUserId(userId);
                baseMapper.insert(curriculumOrder);
                s  = orderNum;
            }else{
                throw new Exception("服务器繁忙，请稍等");
            }
        }catch (Exception e){
            throw new Exception("服务器繁忙，请稍等");
        }finally {
            //放锁
            lock.unlock();
        }

        return s;
    }

    @Override
    public void payNotify(Map<String, String> params) throws AlipayApiException {

    }
}
